import DefaultNavBar from '@/components/StandNavBar/DefaultNavBar';
import {
  CouponStatus,
  CouponType,
  CouponTypeInvert,
  DiscountType,
  getCouponStatus,
  getValidDate,
  ProductType,
} from '@/dataTransfer/coupon.js';
import emptyCoupon from '@/giftCardSubPack/images/coupon/emptyCoupon.png';
import points from '@/giftCardSubPack/images/coupon/points.png';
import used from '@/giftCardSubPack/images/coupon/used.png';
import down from '@/images/common/down.png';
import up from '@/images/common/up.png';
import { debounce } from '@/utils/helper.js';
import { useShowLoading } from '@/utils/hooks/useShowLoading.js';
import utils from '@/utils/index';
import { Button, Image, ScrollView, Text, View } from '@tarojs/components';
import Taro, { useDidShow } from '@tarojs/taro';
import classNames from 'classnames';
import React, { useEffect, useRef, useState } from 'react';
import { connect } from 'react-redux';
import './index.scss';
import Tabs from './tabs.jsx';

const TAB_LIST = [
  {
    label: '可使用',
    value: CouponType.available,
  },
  {
    label: '已使用',
    value: CouponType.used,
  },
  {
    label: '已过期',
    value: CouponType.expired,
  },
];

const EmptyCoupon = () => {
  return (
    <View className="no-coupon-wrap">
      <View className="no-coupon">
        <Image src={emptyCoupon} className="empty-coupon" />
        {/* <Text className="desc">暂无优惠券</Text> */}
      </View>
    </View>
  );
};

const transActivityType = (activityType, sourceType) => {
  let txt = '不可与商家优惠同时使用';
  if (activityType.length === 1 && activityType[0] == 1) {
    txt = sourceType == 0 ? '不可与商家优惠券同时使用' : '可与商家优惠同时使用';
  } else if (activityType.length === 1 && activityType[0] == 2) {
    txt = '不可与秒杀等营销活动同时使用';
  } else if (activityType.length === 3) {
    txt = '可与商家优惠同时使用';
  }
  return txt;
};

const MoreInfoIcon = ({ isShowMoreInfo, setShowMoreInfo, activityType, sourceType }) => {
  let txt = transActivityType(activityType, sourceType);
  return (
    <View
      onClick={() => {
        setShowMoreInfo(!isShowMoreInfo);
      }}
    >
      <View className="explain-info">{txt}</View>

      <View className="arrowAre">
        {isShowMoreInfo ? (
          <Image className="arrow" src={up}></Image>
        ) : (
          <Image className="arrow" src={down}></Image>
        )}
      </View>
    </View>
  );
};

const CouponTimeRange = ({ item, couponType }) => {
  const { status, timeRange, dayDistance, countdown, thatDay } = getCouponStatus(item, couponType);

  if (countdown) {
    return (
      <View className="time-range will-expire">
        <View className="will-expire-left">
          {status == CouponStatus.willExpire ? '距离过期还剩' : '距离可使用还剩'}
        </View>
        <View className="will-expire-right">
          <View className="outer">
            <View className="inner">{countdown[0]}</View>
          </View>

          <Image className="points" src={points}></Image>

          <View className="outer">
            <View className="inner">{countdown[1]}</View>
          </View>

          <Image className="points" src={points}></Image>

          <View className="outer">
            <View className="inner">{countdown[2]}</View>
          </View>
        </View>
      </View>
    );
  }

  if (thatDay) {
    return <View className="time-range">{thatDay}可用</View>;
  }

  return (
    <>
      <View className="time-range omit-1">
        {timeRange[0]}-{timeRange[1]}
      </View>
      {dayDistance && <View className="time-range">{dayDistance}天后可用</View>}
    </>
  );
};

const CouponUse = ({
  item: {
    startTime,
    endTime,
    configId,
    couponId,
    sourceType,
    type,
    orgId,
    merchantId,
    minAmount,
    discountAmount,
  },
  now,
}) => {
  const handleUseCoupon = () => {
    if (type == 1 || type == 3) {
      //商家券--券适用商品列表
      let name =
        minAmount > 0
          ? type == 1
            ? `满${minAmount}减${discountAmount}`
            : `满${minAmount}打${discountAmount}折`
          : '无门槛';
      Taro.navigateTo({
        url: `/giftCardSubPack/couponProducts/index?configId=${configId}&couponId=${couponId}&sourceType=${sourceType}&name=${name}`,
      });
    } else if (type == 2 || type == 4) {
      //外卖券
      if (sourceType == 0) {
        //平台--商户列表页
        Taro.navigateTo({
          url: `/giftCardSubPack/couponShopList/index?configId=${configId}&couponId=${couponId}&sourceType=${sourceType}`,
        });
      } else if (sourceType == 1) {
        //商家--商家外卖详情页
        Taro.navigateTo({
          url:
            '/mainSubPack/takeOutShop/index' + '?' + 'orgId=' + orgId + '&merchantId=' + merchantId,
        });
      }
    }
  };

  if (now >= getValidDate(startTime) && now < getValidDate(endTime)) {
    return (
      <View className="coupon-use customePageBorderStyle" onClick={handleUseCoupon}>
        <View className="btn customePageStyle">立即使用</View>
      </View>
    );
  }

  return null;
};

const StoreCouponInfo = ({ couponDetail = {}, index, couponType, now, setIsShowMore }) => {
  const {
    type,
    sourceType,
    configId,
    merchantName,
    productType,
    minAmount,
    discountAmount,
    maxDiscountAmount = -1,
    couponNo,
    couponId,
    activityType,
    isShowMore,
    categorys = [],
  } = couponDetail;

  const isRebate = type === DiscountType.rebate || type === DiscountType.rebateT;

  // let txt = transActivityType(activityType, sourceType);

  return (
    <View key={couponId + configId} className="couponItem">
      <View
        className={classNames('coupon-item', {
          more: isShowMore,
        })}
      >
        {couponType === CouponType.used && <Image className="watermark" src={used}></Image>}
        <View className="left">
          <MoreInfoIcon
            {...{
              isShowMoreInfo: isShowMore,
              setShowMoreInfo: setIsShowMore.bind(null, index),
              activityType,
              sourceType,
            }}
          ></MoreInfoIcon>

          <View className="coupon-info">
            {(sourceType == 1
              ? merchantName + (productType === ProductType.all ? '全部' : '部分')
              : '商城' +
                (productType === ProductType.all ? '全品类' : categorys.join('、') + '类')) +
              '商品可用'}
          </View>
          <View className="coupon-time-range">
            <CouponTimeRange
              couponType={couponType}
              item={couponDetail}
              now={now}
            ></CouponTimeRange>
          </View>
        </View>

        <View className="right">
          <View
            className={classNames('coupon-price customePageStyle', {
              off: !isRebate,
            })}
          >
            {isRebate ? (
              <>
                <Text className="unit">¥</Text>
                <Text className="price">{discountAmount}</Text>
              </>
            ) : (
              <>
                <Text className="unit">{discountAmount}</Text>
                <Text className="price">折</Text>
              </>
            )}
          </View>
          <View className="coupon-discount">
            {minAmount > 0 ? (
              isRebate ? (
                <View className="min-amount">
                  满{minAmount}减{discountAmount}
                </View>
              ) : (
                <View className="min-amount">
                  满{minAmount}打{discountAmount}折
                </View>
              )
            ) : (
              <View className="min-amount">无门槛</View>
            )}
          </View>

          {couponType === CouponType.available && (
            <CouponUse item={couponDetail} now={now}></CouponUse>
          )}
        </View>
      </View>

      {isShowMore ? (
        <View className="more-info">
          <View className="more-info-item">券编号：{couponNo}</View>
          {/* <View className="more-info-item line">{txt}</View> */}
          {!isRebate && maxDiscountAmount !== -1 && (
            <View className="more-info-item line">最大优惠{maxDiscountAmount}元</View>
          )}
        </View>
      ) : null}
    </View>
  );
};

const TakeOutCouponInfo = ({ couponDetail = {}, index, couponType, now, setIsShowMore }) => {
  const {
    type,
    sourceType,
    configId,
    orgName,
    logoUrl,
    productType,
    minAmount,
    discountAmount,
    maxDiscountAmount = -1,
    couponNo,
    couponId,
    activityType,
    isShowMore,
    categorys = [],
  } = couponDetail;

  const isRebate = type === DiscountType.rebate || type === DiscountType.rebateT;

  return (
    <View key={couponId + configId} className="couponItem">
      <View
        className={classNames('coupon-item-takeout', {
          more: isShowMore,
        })}
      >
        {couponType === CouponType.used && <Image className="watermark" src={used}></Image>}
        <View className="top">
          <View className="left">
            <Image className="logo" src={logoUrl}></Image>
          </View>
          <View className="middle">
            <View className="coupon-info">
              {sourceType == 1
                ? orgName + '外卖专享'
                : productType === ProductType.all
                ? '外卖店铺专享'
                : categorys.join('、') + '外卖专享'}
            </View>
            <View className="coupon-time-range">
              <CouponTimeRange
                couponType={couponType}
                item={couponDetail}
                now={now}
              ></CouponTimeRange>
            </View>
          </View>
          <View className="right">
            <View className="rightCon customePageStyle">
              <View
                className={classNames('coupon-price', {
                  off: !isRebate,
                })}
              >
                {isRebate ? (
                  <>
                    <Text className="unit">¥</Text>
                    <Text className="price">{discountAmount}</Text>
                  </>
                ) : (
                  <>
                    <Text className="unit">{discountAmount}</Text>
                    <Text className="price">折</Text>
                  </>
                )}
              </View>
              <View className="coupon-discount">
                {minAmount > 0 ? (
                  isRebate ? (
                    <View className="min-amount">
                      满{minAmount}减{discountAmount}
                    </View>
                  ) : (
                    <View className="min-amount">
                      满{minAmount}打{discountAmount}折
                    </View>
                  )
                ) : (
                  <View className="min-amount">无门槛</View>
                )}
              </View>
            </View>
          </View>
        </View>
        <View className="bottom">
          <MoreInfoIcon
            {...{
              isShowMoreInfo: isShowMore,
              setShowMoreInfo: setIsShowMore.bind(null, index),
              activityType,
              sourceType,
            }}
          ></MoreInfoIcon>
          {couponType === CouponType.available && (
            <CouponUse item={couponDetail} now={now}></CouponUse>
          )}
        </View>
      </View>

      {isShowMore ? (
        <View className="more-info">
          <View className="more-info-item">券编号：{couponNo}</View>
          {/* {(activityType.length === 0 || (activityType.length === 1 && activityType[0] != 1)) && (
            <View className="more-info-item line">不可与秒杀等营销活动同时使用</View>
          )}
          {sourceType == 0 &&
            (activityType.length === 0 || (activityType.length === 1 && activityType[0] != 2)) && (
              <View className="more-info-item line">不可与商家优惠券同时使用</View>
            )} */}
          {!isRebate && maxDiscountAmount !== -1 && (
            <View className="more-info-item line">最大优惠{maxDiscountAmount}元</View>
          )}
        </View>
      ) : null}
    </View>
  );
};

const CouponInfo = ({ couponDetail = {}, index, couponType, now, setIsShowMore }) => {
  const { type } = couponDetail;

  if (type == 1 || type == 3) {
    return (
      <StoreCouponInfo
        couponDetail={couponDetail}
        index={index}
        couponType={couponType}
        now={now}
        setIsShowMore={setIsShowMore}
      />
    );
  } else if (type == 2 || type == 4) {
    return (
      <TakeOutCouponInfo
        couponDetail={couponDetail}
        index={index}
        couponType={couponType}
        now={now}
        setIsShowMore={setIsShowMore}
      />
    );
  } else {
    return null;
  }
};

const MyCoupon = ({ loading, dispatch, myCouponList, myCouponListFinished }) => {
  useShowLoading(loading, ['giftCard/myCoupon']);

  const isNeedReload = useRef(false);

  const [couponType, setCouponType] = useState(CouponType.available);
  const [now, setNow] = useState(Date.now());

  const [page, setPage] = useState(1);

  const isAvailable = couponType === CouponType.available;

  const handleTabChanged = (index) => {
    // 切换tab, 清空列表
    dispatch({ type: 'giftCard/resetMyCouponList' });

    setPage(1);
    setCouponType(TAB_LIST[index].value);
  };

  const setIsShowMore = (index, value) => {
    let tmp = [...myCouponList];
    tmp[index].isShowMore = value;

    dispatch({
      type: 'giftCard/setMyCouponList',
      payload: tmp,
    });
  };

  // 获取列表数据
  useEffect(() => {
    dispatch({
      type: 'giftCard/myCoupon',
      payload: {
        status: couponType,
        page,
        pageSize: 10,
      },
    });
  }, [couponType, page]);

  // 离开页面清空
  useEffect(() => {
    return () => {
      dispatch({ type: 'giftCard/resetMyCouponList' });
    };
  }, []);

  // 定时更新当前时间, 用于计算倒计时
  useEffect(() => {
    if (couponType !== CouponType.available) {
      return;
    }

    const timer = setInterval(() => {
      setNow(Date.now());
    }, 1000);

    return () => {
      clearInterval(timer);
    };
  }, [couponType]);

  // 从 去领券页面 返回 需要重新获取数据
  useDidShow(() => {
    console.log('========isNeedReload==========', isNeedReload);
    if (!isNeedReload.current) {
      return;
    }

    isNeedReload.current = false;
    dispatch({ type: 'giftCard/resetMyCouponList' });

    if (page === 1) {
      dispatch({
        type: 'giftCard/myCoupon',
        payload: {
          status: couponType,
          page,
          pageSize: 10,
        },
      });
    } else {
      setPage(1);
    }
  });

  const handleScrollToLower = debounce(() => {
    if (myCouponListFinished) {
      return;
    }

    setPage(page + 1);
  }, 2000);

  return (
    <>
      <View className="myCoupon">
        <View
          className="statusTabs"
          style={{ top: 0 + 'px' }}
        >
          <Tabs tabsList={TAB_LIST} getCurrentTab={handleTabChanged} />
        </View>

        <ScrollView
          className="wrap"
          enableFlex
          scrollY
          style={{
            height: `calc(${[
              '100vh',
              Taro.$titleHeight + 'px',
              Taro.$statusBarHeight + 'px',
              // 上面的 可使用 / 不可使用 高度
              utils.getSizeByScale(122) + 'px',
              // 底部的立即领取
              utils.getSizeByScale(isAvailable ? 158 : 0) + 'px',
            ].join(' - ')})`,
          }}
          lowerThreshold={240}
          onScrollToLower={handleScrollToLower}
        >
          <View
            className={classNames('coupon', {
              [CouponTypeInvert[couponType] ?? 'unknown']: true,
            })}
          >
            {(!myCouponList || !myCouponList.length) && myCouponListFinished ? (
              <EmptyCoupon></EmptyCoupon>
            ) : (
              myCouponList?.map((item, index) => (
                <CouponInfo
                  key={item?.couponId}
                  couponDetail={item}
                  index={index}
                  couponType={couponType}
                  now={now}
                  setIsShowMore={setIsShowMore}
                />
              ))
            )}
          </View>

          {isAvailable && myCouponListFinished && myCouponList && myCouponList.length > 8 ? (
            <View className="end">- 我是有底线的 -</View>
          ) : null}
        </ScrollView>

        {isAvailable ? (
          <View
            className="btnBox"
            onClick={() => {
              isNeedReload.current = true;
              Taro.navigateTo({ url: '/giftCardSubPack/couponCenter/index' });
            }}
          >
            <Button className="btn customePageBackgroundStyle">去领券</Button>
          </View>
        ) : null}
      </View>
    </>
  );
};
export default connect(({ giftCard, loading }) => ({
  loading,
  myCouponList: giftCard.myCouponList,
  myCouponListFinished: giftCard.myCouponListFinished,
}))(MyCoupon);
